package cn.net.susan.service.order;

import cn.net.susan.entity.auth.JwtUserEntity;
import cn.net.susan.entity.order.TradeConditionEntity;
import cn.net.susan.entity.order.TradeEntity;
import cn.net.susan.enums.OrderStatusEnum;
import cn.net.susan.enums.PayStatusEnum;
import cn.net.susan.helper.IdGenerateHelper;
import cn.net.susan.mapper.order.TradeItemMapper;
import cn.net.susan.mapper.order.TradeMapper;
import cn.net.susan.util.AssertUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 订单保存 服务层
 *
 * @author 苏三 该项目是知识星球：java突击队 的内部项目
 * @date 2024-05-30 15:33:03
 */
@Service
public class TradeSaveService {

    @Autowired
    private TradeMapper tradeMapper;
    @Autowired
    private TradeItemMapper tradeItemMapper;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private IdGenerateHelper idGenerateHelper;


    @DS("sharding")
    public void createTrade(JwtUserEntity currentUserInfo, TradeEntity tradeEntity) {
        tradeEntity.setId(idGenerateHelper.nextId());
        tradeEntity.setUserId(currentUserInfo.getId());
        tradeEntity.setUserName(currentUserInfo.getUsername());
        tradeEntity.setOrderStatus(OrderStatusEnum.CREATE.getValue());
        tradeEntity.setPayStatus(PayStatusEnum.WAIT_PAY.getValue());
        tradeEntity.setOrderTime(new Date());

        transactionTemplate.execute((status) -> {
                    tradeMapper.insert(tradeEntity);
                    tradeEntity.getTradeItemEntityList().forEach(x -> {
                        x.setTradeId(tradeEntity.getId());
                        x.setCode(tradeEntity.getCode());
                    });
                    tradeItemMapper.batchInsert(tradeEntity.getTradeItemEntityList());
                    return Boolean.TRUE;
                }
        );
    }


    @DS("sharding")
    public void checkRepeat(TradeEntity tradeEntity) {
        if (!StringUtils.hasLength(tradeEntity.getCode())) {
            return;
        }

        TradeConditionEntity tradeConditionEntity = new TradeConditionEntity();
        tradeConditionEntity.setCode(tradeEntity.getCode());
        List<TradeEntity> tradeEntities = tradeMapper.searchByCondition(tradeConditionEntity);
        AssertUtil.isTrue(CollectionUtils.isEmpty(tradeEntities), "该订单编号已存在");
    }

}
